package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**springSecurity的service
 * @author hql
 * @date 2019-12-11 13:59
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查找数据库的用户对应的信息
       User user = userService.findByUsername(username);
       //判断用户是否为空
        if (user == null){
            return null;
        }
        //创建授予权限和角色的集合
        List<GrantedAuthority> list=new ArrayList<>();
        //拿到用户所对应的所有角色的集合
        Set<Role> roles = user.getRoles();
        //遍历角色，并为其添加角色
        for (Role role : roles) {
            //再集合添加用户所有的角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //拿到每个角色所对应的权限的集合
            Set<Permission> permissions = role.getPermissions();
            //遍历权限集合
            for (Permission permission : permissions) {
                //为每个角色附上所对应的权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //创建含有授权和角色已经用户名和密码的User对象(注意是spring security提供的User)
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);

        return userDetails;
    }
}
